import axios from "axios";
import { ElMessage } from "element-plus";
const instance = axios.create({
  baseURL: window.config.baseUrl,
});

/**
 * Send a request to the server and return a Promise.
 * If the request is successful, the Promise is resolved with the server's response.
 * If the request fails, the Promise is rejected with the server's error message.
 * If the request is successful but the server returns an error code, the Promise is
 * rejected with the server's error message. If the error code is not 200, the error
 * message is displayed to the user using ElMessage.error.
 * @param {Object} config - The config object to send to the server.
 * @returns {Promise} - A Promise that is resolved or rejected based on the server's response.
 */
const request = (config) => {
  return new Promise((resolve, reject) => {
    instance(config)
      .then((response) => {
        const data = response.data;
        if (data.code == 200) {
          resolve(data);
        } else {
          ElMessage.error(data.message);

          reject(data);
        }
      })
      .catch((error) => {
        reject(error);
      });
  });
};

export default request;
